// include/bigintaddsub.h
#pragma once

#include <algorithm>
#include <iostream>
#include <string>

class BigInt {
public:
    BigInt() : digits_("0"), isNegative_(false) {}

    explicit BigInt(const std::string& value) {
        parse(value);
    }

    // Step3: 通过 long long 构造并转换为内部字符串
    explicit BigInt(long long value) {
        if (value < 0) {
            isNegative_ = true;
            value = -value;
        } else {
            isNegative_ = false;
        }
        digits_ = std::to_string(value);
        normalizeZero();
    }

    friend std::ostream& operator<<(std::ostream& os, const BigInt& obj) {
        if (obj.isNegative_ && obj.digits_ != "0") {
            os << '-';
        }
        os << obj.digits_;
        return os;
    }

private:
    std::string digits_;
    bool isNegative_{false};

    void parse(const std::string& value) {
        if (value.empty()) {
            digits_ = "0";
            isNegative_ = false;
            return;
        }

        std::size_t index = 0;
        if (value[index] == '+' || value[index] == '-') {
            isNegative_ = (value[index] == '-');
            ++index;
        } else {
            isNegative_ = false;
        }

        digits_.clear();
        for (; index < value.size(); ++index) {
            char c = value[index];
            if (c >= '0' && c <= '9') {
                digits_.push_back(c);
            }
        }

        if (digits_.empty()) {
            digits_ = "0";
            isNegative_ = false;
        } else {
            removeLeadingZeros();
        }

        normalizeZero();
    }

    void removeLeadingZeros() {
        auto it = digits_.begin();
        while (it != digits_.end() - 1 && *it == '0') {
            ++it;
        }
        digits_.erase(digits_.begin(), it);
    }

    void normalizeZero() {
        if (digits_ == "0") {
            isNegative_ = false;
        }
    }
};